<template>
  <div id="createCourse">
    <!-- 就诊时间选择 -->
    <div class='mc' v-show='isTime' @click.stop='toggle(0)'></div>
    <div class='datetime'>
      <div class='top'>
        <a @click.stop='toggle(0)'>取消</a>
        <a @click.stop='sureTime'>确定</a>
      </div>
      <mt-picker :slots="slotsTime" @change="onValuesChangeTime"></mt-picker>
    </div>
    <header>
      <i @click="goBack()"></i>
      <div>{{course_Type}}</div>
    </header>
    <div class="swiper-container swipe" id="outSwiper">
      <div class="swiper-wrapper">
        <div class="swiper-slide">
          <ul class='single'>
            <li class='no-border'>
              <a>
                <label>选择直播类型:</label>
                <span class='red'>保存后不可更改</span>
              </a>
              <a class="liveType">
                <label @change="liveType()" @click="hide1()">
                  <input type="radio" v-model="issingleFree" value='free'>
                  <i>免费</i>
                </label>
                <label @change="liveType()" @click="show1()">
                  <input type="radio" v-model="issingleFree" value='charge'>
                  <i>收费</i>
                </label>
              </a>
              <a class="liveType">
                <input type="text" placeholder="输入金额" v-model='singlePrice' style="width:1.1rem" v-if="show">
              </a>
            </li>
            <li>
              <a>
                <label>直播主题:</label>
                <input type="text" placeholder="请输入直播主题" v-model='singleLiveTheme' />
              </a>
            </li>
            <li @click='toggle(1)'>
              <a>
                <label>开始时间:</label>
                <div class='time'>{{pickerValue || "请选择开播时间"}}</div>
              </a>
            </li>
            <li class='no-border'>
              <a class="descTitle">
                <label>课程介绍:</label>
              </a>
            </li>
            <li class="">
              <a class="courseDesc">
                <textarea placeholder="请输入课程介绍" v-model='singleCourseDesc'></textarea>
              </a>
            </li>
            <li class='no-border'>
              <a class="uploadImg">
                <div class="img" v-if="isShow">
                  <img class="selectImg" :src="singleUrl1" width="50" height="50" />
                </div>
                <div class="upfileDiv">
                  <el-upload class="avatar-uploader" :action='$api.baseURLUpload+"/photos/upload_shop"' :show-file-list="false"
                    :on-success="(res,file)=>{
					                    return handleAvatarSuccess(res,file,1)
					                  }"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="!singleUrl1" :src="singleUrl1" class="avatar">
                    <i v-else class="uploader">上传课程照片</i>
                  </el-upload>
                </div>

              </a>
            </li>
            <div class="border-8"></div>
            <li class='no-border'>
              <a class="descTitle">
                <label>老师介绍:</label>
              </a>
            </li>
            <li class="">
              <a class="courseDesc">
                <textarea placeholder="请填写个人介绍" v-model='v_desc'></textarea>
              </a>
            </li>
            <!-- <li>
                <a>
                    <label>地址:</label>
                    <input type="text" placeholder="请输入您所处地址" v-model='v_address' />
                  </a>
            </li> -->
            <li class='no-border'>
              <a class="uploadImg">
                <div class="img" v-if="isShow">
                  <img class="selectImg" :src="singleUr" width="50" height="50" />
                </div>
                <div class="upfileDiv">
                  <el-upload class="avatar-uploader" :action='$api.baseURLUpload+"/photos/upload_shop"' :show-file-list="false"
                    :on-success="(res,file)=>{
                                              return handleAvatarSuccess1(res,file,1)
                                            }"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="!singleUrl1" :src="singleUr" class="avatar">
                    <i v-else class="uploader">上传个人照片</i>
                  </el-upload>
                </div>

              </a>
            </li>
            <div class="border-8"></div>
            <li>
              <a>
                <label>视频名称:</label>
                <input type="text" placeholder="请输入视频名称" v-model='v_name' />
              </a>
            </li>
            <div id="uploadFile">
              <div class="upfileDiv">
                <img src="../../image/icon_upload_file.png" width="120" alt="">
                <iframe name="myiframe" width="0" height="0" scrolling="no" style="display: none"></iframe>
                <form id='myupload' :action='$api.baseURLUpload+"/photos/upload_shop"' method='post' enctype='multipart/form-data'
                  target="myiframe">
                  <input type="file" name="file" class="upfile" @change="upfile" />
                </form>

              </div>
              <div class="progress">
                <div class="bar" :style="{width: barWidth+'%'}"></div>
                <div class="upstatus" style="margin-top:10px;"></div>
              </div>
              <div class="mesBox">
                <div class="message">
                  <div>
                    我们支持ogg,mp4,webm等文件格式, 文件小于200M, 请尽量上传高音质音频.
                  </div>
                  <div>
                    请遵守
                    <i class="blue">《版权声明》</i>相关约定, 只上传版权拥有者允许你上传的音频或视频文件
                    <i class="red">如上传盗版内容, 将会导致下架,封号,索赔,甚至被追究刑事责任.</i>
                  </div>
                </div>
              </div>
            </div>
            <li v-if='this.$route.query.type == "hide"'>
              <a @click='singleNext1' class="nextStep">
                完 成
              </a>
            </li>
            <li v-if='this.$route.query.type != "hide"'>
              <a @click='singleNext' class="nextStep">
                完 成
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
  import {
    Indicator
  } from 'mint-ui';
  import {
    Toast
  } from 'mint-ui';
  export default {
    data() {
      return {
        course_Type: '', //课程状态
        url: '', //上传视频连接
        show: false,
        //上传视频的
        barWidth: 0,
        fileName: '',

        isdisabled: true,
        isShow: true, //选择图片是否显示
        //单节课
        issingleFree: 'free', //免费free 收费charge
        // discount: '', //原价
        singlePrice: '', //收费金额
        singleLiveTheme: '', //直播主题
        valuestime: '', //开播时间选择但未确定时的选项
        pickerValue: '', //开播时间  时间选择器
        isTime: false, //是否显示时间选择器
        v_address: '',
        slotsTime: [{
            flex: 1,
            values: function () {
              const date = new Date();
              const year = date.getFullYear();
              const yearArr = [];
              for (var i = year; i < year + 10; i++) {
                yearArr.push(i);
              }
              return yearArr;
            }(),
            className: 'slot1',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const monthArr = [];
              for (var i = 1; i < 13; i++) {
                if (i < 10) {
                  monthArr.push('0' + i);
                } else {
                  monthArr.push(i);
                }

              }
              return monthArr;
            }(),
            className: 'slot2',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const dayArr = [];
              for (var i = 1; i < 32; i++) {
                if (i < 10) {
                  dayArr.push('0' + i);
                } else {
                  dayArr.push(i);
                }

              }
              return dayArr;
            }(),
            className: 'slot3',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const hourArr = [];
              for (var i = 0; i < 24; i++) {
                if (i < 10) {
                  hourArr.push('0' + i);
                } else {
                  hourArr.push(i);
                }

              }
              return hourArr;
            }(),
            className: 'slot4',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const minArr = [];
              for (var i = 0; i < 60; i++) {
                if (i < 10) {
                  minArr.push('0' + i);
                } else {
                  minArr.push(i);
                }
              }
              return minArr;
            }(),
            className: 'slot5',
            textAlign: 'center'
          }
        ],
        singleCourseDesc: '', //课程介绍内容
        singleUrl1: require('../../image/bg_pic.png'), //封面

        //老师介绍
        v_desc: '', //个人描述
        v_address: '',
        singleUr: require('../../image/bg_pic.png'), //封面
        v_name: '',
        //系列课
        isFree: 'free', //系列课程  免费free 收费charge
        seriesPrice: '', //系列课价格
        seriesName: '', //系列课名称
        seriesUrl1: require('../../image/bg_pic.png'), //系列课封面
        classNum: '', //排课计划2-100
        classNumTrue: false,
        mySwiper: '', //轮播图选项卡
        cid: "", //新创建课程id
      }
    },
    components: {

    },
    methods: {
      hide1() {
        this.show = false;
      },
      show1() {
        this.show = true;
      },
      //获取课程
      getDetailsData() {
        this.cid = this.$route.query.id;
        this.$api.get(this.$api.baseURLSchool, "select_cid/view_course_user/" + this.cid, {}, r => {
          this.singleLiveTheme = r.data.info.course_name;
          this.pickerValue = r.data.info.starttime
          this.singleUr = r.data.info.teacher_pic
          this.singleUrl1 = r.data.info.course_pic
          this.singleCourseDesc = r.data.info.program
          this.v_desc = r.data.info.teacher_intro
          this.issingleFree = r.data.info.iffree;
          this.singlePrice = r.data.info.charge
          if (r.data.info.iffree == 'charge') {
            this.show = true
          }
        }, err => {
          console.log(err);
        })
      },

      //获取视频
      getVideoByCid() {
        this.cid = this.$route.query.id;
        this.$api.get(this.$api.baseURLSchool, "selectdata2/video?cid=" + this.cid, {}, r => {
          this.v_name = r.data.info[0].v_name;
          this.url = r.data.info[0].url
          if (r.data.ret == 1) {
            this.v_name = r.data.info[0].v_name;
            this.url = r.data.info[0].url
          }
        }, err => {
          console.log(err);
        })
      },

      //上传视频
      upfile: function () {
        var file = $(".upfile")[0].files[0];
        this.fileName = file.name;
        //这里我们判断下类型如果不是视频就返回
        var fileTypes = new Array("ogg", "mp4", "webm"); //定义可支持的文件类型数组
        var fileTypeFlag = "0";
        var newFileName = this.fileName.split('.');
        newFileName = newFileName[newFileName.length - 1];
        for (var i = 0; i < fileTypes.length; i++) {
          if (fileTypes[i] == newFileName) {
            fileTypeFlag = "1";
          }
        }
        if (fileTypeFlag == "0") {
          this.$utils._toast("视频文件必须是ogg、mpeg4、webm格式！");
          return false;
        }
        if (file.size > 200 * 1024 * 1024) {
          this.$utils._toast('上传文件不能超过200M');
          return false;
        }
        var _this = this;
        var reader = new FileReader();
        reader.readAsDataURL(file);
        if (file && fileTypeFlag) {
          //如果选中文件 就上传
          var options = {
            url: this.$api.baseURLUpload + "/photos/upload_shop", //同action
            type: 'post',
            beforeSend: function (xhr) { //请求之前
            },
            uploadProgress: function (event, position, total, percentComplete) {
              //上传的过程
              //position 已上传了多少
              //total 总大小
              //已上传的百分数
              _this.barWidth = percentComplete;
            },
            success: function (data) {
              _this.barWidth = 100;
              if (data.state == 200) {
                _this.$utils._toast("上传成功");
                _this.url = data.result;
              }
            },
            complete: function (xhr) { //请求完成

            },
            error: function (xhr, status, msg) {
              _this.$utils._toast("视频异常！" + xhr.msg);
            }
          };
          $("#myupload").ajaxSubmit(options);
        }
      },


      // 控制日期选择器显示隐藏动画
      toggle(status) { //status 0隐藏 1显示
        if (status) {
          this.isTime = true;
          $(".datetime").addClass("up").removeClass("down");
        } else {
          $(".datetime").addClass("down").removeClass("up");
          this.isTime = false;
        }
      },
      //开播时间
      onValuesChangeTime(picker, values) {
        this.valuestime = values[0] + '-' + values[1] + '-' + values[2] + ' ' + values[3] + ':' + values[4];

        function mGetDate(year, month) {
          var d = new Date(year, month, 0);
          return d.getDate();
        }
        var totalDay = mGetDate(values[0], values[1]); //29 
        const dayArr = [];
        for (var i = 1; i < totalDay + 1; i++) {
          if (i < 10) {
            dayArr.push('0' + i);
          } else {
            dayArr.push(i);
          }
        }
        picker.setSlotValues(2, dayArr)
      },
      //确定开播时间
      sureTime() {
        this.pickerValue = this.valuestime;
        this.toggle(0);
      },
      //上传图片  i 1是单节课图 2是系列课图
      handleAvatarSuccess(res, file, i) {
        if (res.state == 200) {
          if (i == 1) {
            this.singleUrl1 = res.result_origin;
          } else if (i == 2) {
            this.seriesUrl1 = res.result_origin
          }
        }
      },
      handleAvatarSuccess1(res, file, i) {
        if (res.state == 200) {
          this.singleUr = res.result_origin;
        }
      },
      beforeAvatarUpload(file) {
        if (!/image\/\w+/.test(file.type)) {
          this.$utils._toast('请确保文件为图像类型');
          return false;
        }
        if (file.size > 5 * 1024 * 1024) {
          this.$utils._toast('上传图片不能超过5M');
          return false;
        }
      },
      goBack() {
        this.$router.back();
      },
      focus(e) {
        setTimeout(function () {
          e.target.scrollIntoView(true);
        }, 200);
      },
      // 完成
      singleNext1() {
        this.url = this.$route.query.url
        if (this.singleLiveTheme && this.pickerValue && this.singleCourseDesc && this.singleUrl1 &&
          this.v_desc && this.singleUr && this.url && this.v_name) {
          const data_course = new Object(); //课程内容
          const data_video = new Object(); //视频内容
          data_video.url = this.url; //视频连接
          data_video.userid = localStorage.getItem("loginMobile"); //视频连接
          data_video.v_name = this.v_name; //视频名称
          data_course.iffree = this.issingleFree;
          data_course.course_name = this.singleLiveTheme; //直播主题
          data_course.starttime = this.pickerValue; //开始时间
          data_course.program = this.singleCourseDesc; //课程介绍
          data_course.course_pic = this.singleUrl1; //课程照片
          data_course.teacher_intro = this.v_desc; //老师介绍
          data_course.teacher_pic = this.singleUr; //老师照片
          data_course.teacher_name = localStorage.getItem("doctorName");; //老师姓名
          data_course.uid = localStorage.getItem("loginMobile");
          data_course.course_type = 0;
          const singleClass = {
            data_course,
            data_video
          };
          if (this.issingleFree == 'free') {} else {
            data_course.charge = this.singlePrice; //原价
          }
          //单节课程
          this.$api.post(this.$api.baseURLSchool, "course_video_add", singleClass, r => {
            this.cid = r.data.info.cid;
            this.$router.push({
              path: '/homeDetail',
              query: {
                name: 'createSingle',
                id: this.cid
              }
            });
          }, err => {
            console.log(err);
          })
        } else {
          this.$utils._toast('请检查上述内容是否输入完整');
        }
      },
      // 完成
      singleNext() {
        if (this.singleLiveTheme && this.pickerValue && this.singleCourseDesc && this.singleUrl1 &&
          this.v_desc && this.singleUr && this.url && this.v_name) {
          const data_course = new Object(); //课程内容
          const data_video = new Object(); //视频内容
          data_video.url = this.url; //视频连接
          data_video.userid = localStorage.getItem("loginMobile"); //视频连接
          data_video.v_name = this.v_name; //视频名称
          data_course.iffree = this.issingleFree;
          data_course.course_name = this.singleLiveTheme; //直播主题
          data_course.starttime = this.pickerValue; //开始时间
          data_course.program = this.singleCourseDesc; //课程介绍
          data_course.course_pic = this.singleUrl1; //课程照片
          data_course.teacher_intro = this.v_desc; //老师介绍
          data_course.teacher_pic = this.singleUr; //老师照片
          data_course.teacher_name = localStorage.getItem("doctorName");; //老师姓名
          data_course.uid = localStorage.getItem("loginMobile");
          data_course.course_type = 0;
          const singleClass = {
            data_course,
            data_video
          };
          console.log('singleClass', singleClass)
          if (this.issingleFree == 'free') {} else {
            data_course.charge = this.singlePrice; //原价
          }
          //创建免费单节课程
          if (this.$route.query.type == 'add') {
            this.$api.post(this.$api.baseURLSchool, "course_video_add", singleClass, r => {
              this.cid = r.data.info.cid;
              this.$router.push({
                path: '/homeDetail',
                query: {
                  name: 'createSingle',
                  id: this.cid
                }
              });
            }, err => {
              console.log(err);
            })
          } else {
            data_course.id = this.$route.query.id
            this.$api.post(this.$api.baseURLSchool, "course_video_edit", singleClass, r => {
              this.cid = r.data.info.cid;
              this.$router.push({
                path: '/homeDetail',
                query: {
                  name: 'createSingle',
                  id: this.cid
                }
              });
            }, err => {
              console.log(err);
            })
          }
        } else {
          this.$utils._toast('请检查上述内容是否输入完整');
        }
      },
    },
    created() {
      console.log(this.$route.query.type)
      if (this.$route.query.type == 'add' || this.$route.query.type == 'hide') {
        this.course_Type = '创建课程'
      } else {
        this.course_Type = '编辑课程',
          this.barWidth = 100;
        this.getDetailsData(); //获取课程
        this.getVideoByCid(); //获取视频
      }

    },
    mounted() {
      if (this.$route.query.type == 'hide') {
        $('#uploadFile').css('display', 'none')
      }
      this.mySwiper = new Swiper('#outSwiper', {
        resistanceRatio: 0,
        onSlideChangeStart: function (swiper) {
          var index = swiper.activeIndex;
          $('.nav div').removeClass();
          $('.nav div').eq(index).addClass("active");
        }
      });
      var _this = this;
      $('.nav div').click(function () {
        _this.mySwiper.slideTo($(this).index());
        $(this).addClass('active').siblings().removeClass();
      });
    }
  }

</script>
<style lang="scss">
  .uploader {
    width: 0.5rem;
    height: 0.5rem;
    line-height: 0.25rem;
    font-size: 10px;
    display: inline-block;
    border: 1px dashed #eee;
  }

  #uploadFile p {
    margin-top: 10px;
  }

  #uploadFile .mesBox .message {
    background: transparent;
  }

</style>
